package pers.vic.boot.console.util;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 描述:国际化工具类  依赖于spring
 * @author Vic.xu
 * @date 2021-12-10 10:46
 */
@Component
public class I18nUtil {

    private static MessageSource messageSource;

    private static SessionLocaleResolver localeResolver;

    public I18nUtil(MessageSource messageSource, SessionLocaleResolver localeResolver) {
        I18nUtil.messageSource = messageSource;
        I18nUtil.localeResolver = localeResolver;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String code) {
        if (messageSource == null) {
            return code;
        }
        try {
            return messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return code;
        }
    }

    /**
     *  切换一次  在当前线程中生效
     * @param locale
     */
    public static void switchOnce(Locale locale) {
        LocaleContextHolder.setLocale(locale);
    }

    /**
     * 切换 Locale
     * @param request
     * @param response
     * @param locale   Locale.CHINA; Locale.US
     * @return
     */
    public static boolean switchLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        if (localeResolver == null) {
            return false;
        }


        localeResolver.setLocale(request, response, locale);
        return true;
    }

}
